﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using ApplicationLibrary;
using ApplicationLibrary.DBManager;
using ApplicationLibrary.ExtendedControls;
using ApplicationLibrary.Preferences;
using ApplicationLibrary.SqlConnector;
using Plumber.Accounting.ModuleData;
using Plumber.Accounting.Preferences;
using Plumber.Masters.ModuleData;

namespace Plumber.Accounting.Forms
{
    public partial class AccountingMasters : DocumentForm
    {
        private const string JournalEntrySlave = "JOURNALENTRSLAVE";
        private PreferencesManager<AccountingPref> myAccountingPref = null;
        private AccountingPref AccountingPref = null;

        public AccountingMasters()
            : base(Properties.Resources.FN_Quotations)
        {
            InitializeComponent();
            keyControl = codMaster;
        }

        #region Virtual Method

        protected override IRadarParameters GetKeyFromDocument()
        {
            return new RadarMasterParam(cbbType.GetValue<string>(), codMaster.Text);
        }

        protected override void OnAttachData()
        {
            dbManager = new dbmanagerAccountingMasters("AccountingMasters", new RadarMasterForm(RadarMasterForm.Module.Accounting), this);
            dbManager.AddMaster(this, PL_Masters.Name, true);
            dbManager.AddSlave(JournalEntrySlave, false);

            myAccountingPref = new PreferencesManager<AccountingPref>(formName, null);
            AccountingPref = myAccountingPref.ReadPreference();

            ManageTabJE(AccountingPref.EnableLink);

            rdrTitle.RadarForm = new RadarTitles();
            rdrTitle.DescriptionControl = lblTitleDesc;

            cbbType.AttachDataReader(new RRMasterTypeForAccountingMaster());

            ntbFrom.Prefix = Properties.Resources.CurrencySimbol;
            ntbTo.Prefix = Properties.Resources.CurrencySimbol;

            if (AccountingPref.EnableLink)
            {
                dgwJE.AutoGenerateColumns = false;
                dgwJE.DataSource = dbManager.Dataset.Tables[JournalEntrySlave];
                dgwJE.AddReadOnlyColumn(PL_JournalEntry.JournalNo, true);
                dgwJE.AddReadOnlyColumn(PL_JournalEntry.PostingDate, true);
                dgwJE.AddReadOnlyColumn(PL_JournalEntryDetail.Description, true);
                dgwJE.AddReadOnlyColumn(PL_JournalEntryDetail.From, true);
                dgwJE.AddReadOnlyColumn(PL_JournalEntryDetail.To, true);
            }
        }

        protected override void OnBindData()
        {
            BindControl(cbbType, PL_Masters.Type, "SelectedValue", NullValue.NotSet, Findable.YES);

            BindControl(codMaster, PL_Masters.Code, Findable.YES);
            BindControl(txtCompany, PL_Masters.Description, Findable.YES);
            BindControl(ckbBlocked, PL_Masters.Blocked, "DBChecked");
            BindControl(ckbDisabled, PL_Masters.Disabled, "DBChecked");

            BindControl(txtAddress, PL_Masters.Address);
            BindControl(mtbZip, PL_Masters.ZipCode);
            BindControl(txtCity, PL_Masters.City);
            BindControl(txtCounty, PL_Masters.County);
            BindControl(txtPhone1, PL_Masters.Phone1);
            BindControl(txtPhone2, PL_Masters.Phone2);
            BindControl(txtFax, PL_Masters.Fax);
            BindControl(txtRefer1, PL_Masters.Refer1);
            BindControl(txtRefer2, PL_Masters.Refer2);
            BindControl(rdrTitle, PL_Masters.Title);
            BindControl(txtEmail, PL_Masters.Email);

            BindControl(ftbTaxNo, PL_Masters.TaxNo);
            BindControl(ftbFiscalCode, PL_Masters.FiscalCode);

            if (AccountingPref.EnableLink)
            {
                BindControl(dgwJE);
                BindColumn(jec_JENo, PL_JournalEntry.JournalNo);
                BindColumn(jec_Date, PL_JournalEntry.PostingDate);
                BindColumn(jec_Desc, PL_JournalEntryDetail.Description);
                BindColumn(jec_From, PL_JournalEntryDetail.From);
                BindColumn(jec_To, PL_JournalEntryDetail.To);
            }
        }

        protected override bool OnBeforeSave()
        {
            return base.OnBeforeSave();
        }

        protected override void OnPrepareAuxData()
        {
            CalculateTotal();
            dbManager.RadarDocument.FilterType = null;

            base.OnPrepareAuxData();
        }

        protected override void FocusOnNew()
        {
            codMaster.Focus();
        }

        protected override void OnDisableControlsForEdit()
        {
            codMaster.Enabled = false;
            cbbType.Enabled = false;
        }

        #endregion

        #region Events

        private void codAdmin_Validating(object sender, CancelEventArgs e)
        {
            //if (AdministratorReader.Find(codAdmin.Text))
            //{
            //    MessageBox.Show(Properties.Resources.Msg_Administrator,
            //    Properties.Resources.Warning,
            //    MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    e.Cancel = true;
            //}
        }

        #endregion

        private void dgwJE_DataGridViewDoubleClickCell(object sender, DataGridViewDoubleClickArgs e)
        {
            if (e.ColumnName == PL_JournalEntryDetail.JournalNo.Name)
            {
                JournalEntries frm = (JournalEntries)GlobalInfo.OpenForm("Plumber.Plumber.Accounting.Forms.JournalEntries", false);
                frm.FindRecord(new RadarJournalEntryParam(e.CellValue));
            }
        }

        private void cbbType_SelectedValueChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cbbType.GetValue<string>()))
            {
                CodeMode cm = cbbType.dRMasterType.GetValue<CodeMode>(PL_MasterType.CodeMode);
                MasterTypes mt = cbbType.dRMasterType.GetValue<MasterTypes>(PL_MasterType.MasterType);
                dbManager.RadarDocument.FilterType = cbbType.GetValue<string>();

                if (cm != CodeMode.E_IsEmpty)
                    codMaster.ReattachCodeType(cbbType.GetValue<string>());

                this.Text = cbbType.Text;
            }
        }

        private void ManageTabJE(bool visible)
        {
            TabPage tp = tabControl1.TabPages["tpbJE"];
            if (tp == null)
            {
                if (visible)
                    tabControl1.TabPages.Add(tpbJE);
            }
            else
            {
                if (!visible)
                    tabControl1.TabPages.Remove(tpbJE);
            }
        }

        private void CalculateTotal()
        {
            ntbFrom.Double = 0;
            ntbTo.Double = 0;
            foreach (DataGridViewRow dr in dgwJE.Rows)
            {
                if (!dr.IsNewRow)
                {
                    ntbFrom.Double += DataGridViewRowValues.GetValue<double>(dr, PL_JournalEntryDetail.From);
                    ntbTo.Double += DataGridViewRowValues.GetValue<double>(dr, PL_JournalEntryDetail.To);
                }
            }
        }

        private void ckbRestraint_CheckedChanged(object sender, EventArgs e)
        {
        }
    }

    #region dbmanager AccountingMasters

    /// <summary>
    /// Classe derivata per gestioni particolari
    /// </summary>
    internal class dbmanagerAccountingMasters : DBManager
    {
        private const string JournalEntrySlave = "JOURNALENTRSLAVE";

        public dbmanagerAccountingMasters(string name, RadarForm radar, DocumentForm document)
            : base(name, radar, document)
        { }

        protected override void dAdapter_MasterRowUpdating(object sender, SqlABRowUpdatingEventArgs e)
        {
            if (e.StatementType == StatementType.Insert)
            {
                if (e.Row[PL_Masters.IsAccountingType.Name] == System.DBNull.Value)
                    e.Row[PL_Masters.IsAccountingType.Name] = 1;
            }
            base.dAdapter_MasterRowUpdating(sender, e);
        }

        protected override string CreateMasterQuery()
        {
            this.Table = new PL_Masters();
            QueryBuilder qB = new QueryBuilder();
            qB.AddSelect();
            qB.AddFrom(PL_Masters.Name);
            qB.AddCompare<bool>(PL_Masters.IsAccountingType, true);
            qB.AddCompare(PL_Masters.Code, "@p1");
            qB.AddCompare(PL_Masters.Type, "@p2");

            return qB.Query;
        }

        protected override List<SqlABParameter> CreateMasterParam()
        {
            List<SqlABParameter> PList = new List<SqlABParameter>();

            SqlABParameter sParam1 = new SqlABParameter("@p1", PL_Masters.Code);
            sParam1.Value = "";
            PList.Add(sParam1);

            SqlABParameter sParam2 = new SqlABParameter("@p2", PL_Masters.Type);
            sParam2.Value = "";
            PList.Add(sParam2);
            return PList;
        }

        protected override string CreateSlaveQuery(string name)
        {
            QueryBuilder qb = new QueryBuilder();
            if (name == JournalEntrySlave)
            {
                qb.SetQualified = true;
                qb.AddSelect();
                qb.AddFrom(PL_JournalEntryDetail.Name);
                qb.AddJoin(QueryBuilder.JoinType.INNER, PL_JournalEntry.JournalNo, PL_JournalEntryDetail.JournalNo);
                qb.AddCompare(PL_JournalEntryDetail.Type, "@p4");
                qb.AddCompare(PL_JournalEntryDetail.Code, "@p5");
                qb.Where += string.Format(" AND ({0} BETWEEN @p6 AND  @p7 OR {1} = '0')", PL_JournalEntry.PostingDate.Name,
                    PL_JournalEntryDetail.Close.Name);
            }

            return qb.Query;
        }

        protected override List<SqlABParameter> CreateSlaveParam(string name)
        {
            List<SqlABParameter> PList = new List<SqlABParameter>();
            if (name == JournalEntrySlave)
            {
                SqlABParameter p1 = new SqlABParameter("@p4", PL_JournalEntryDetail.Type);
                p1.Value = "";
                PList.Add(p1);
                SqlABParameter p2 = new SqlABParameter("@p5", PL_JournalEntryDetail.Code);
                p2.Value = "";
                PList.Add(p2);
                SqlABParameter p3 = new SqlABParameter("@p6", PL_JournalEntry.PostingDate);
                p3.Value = DateTime.Today;
                PList.Add(p3);
                SqlABParameter p4 = new SqlABParameter("@p7", PL_JournalEntry.PostingDate);
                p4.Value = DateTime.Today;
                PList.Add(p4);
            }
            return PList;
        }

        protected override void SetParameters(IRadarParameters key, DBCollection collection)
        {
            if (collection.Name == PL_Masters.Name)
            {
                collection.Parameter[0].Value = key[0];
                collection.Parameter[1].Value = key[1];
            }
            else if (collection.Name == JournalEntrySlave)
            {
                collection.Parameter[0].Value = key[1];
                collection.Parameter[1].Value = key[0];
                collection.Parameter[2].Value = new DateTime(GlobalInfo.CurrentDate.Year, 1, 1);
                collection.Parameter[3].Value = new DateTime(GlobalInfo.CurrentDate.Year, 12, 31);
            }
        }
    }

    #endregion
}